// pages/contract-detail/index.js
Page({
  data: {
    contractId: '',
    contractData: null,
    loading: false
  },

  onLoad(options) {
    if (options.contractId) {
      this.setData({ contractId: options.contractId });
      this.loadContractDetail();
    } else {
      wx.showToast({
        title: '合同ID缺失',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载合同详情
  async loadContractDetail() {
    this.setData({ loading: true });
    try {
      const res = await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'getContractInfo',
          contractId: this.data.contractId
        }
      });

      if (res.result.res.code === 200) {
        const contractData = res.result.res.data;
        // 格式化日期
        // 格式化创建时间
        let createTimeStr = '未设置';
        if (contractData.createTime) {
          if (contractData.createTime instanceof Date) {
            createTimeStr = this.formatDateTime(contractData.createTime);
          } else if (typeof contractData.createTime === 'object' && contractData.createTime.constructor.name === 'ServerDate') {
            // 云数据库的ServerDate对象，需要特殊处理
            createTimeStr = '已创建';
          } else {
            createTimeStr = this.formatDateTime(new Date(contractData.createTime));
          }
        }

        const formattedData = {
          ...contractData,
          startDateStr: this.formatDate(contractData.startYear, contractData.startMonth, contractData.startDay),
          endDateStr: this.formatDate(contractData.endYear, contractData.endMonth, contractData.endDay),
          deliveryDateStr: this.formatDate(contractData.deliveryYear, contractData.deliveryMonth, contractData.deliveryDay),
          createTime: createTimeStr,
          statusText: this.getStatusText(contractData.status),
          statusClass: this.getStatusClass(contractData.status)
        };
        this.setData({
          contractData: formattedData,
          loading: false
        });
      } else {
        wx.showToast({
          title: res.result.res.msg || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载合同详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 格式化日期
  formatDate(year, month, day) {
    if (year && month && day) {
      return `${year}年${month}月${day}日`;
    }
    return '未设置';
  },

  // 格式化日期时间
  formatDateTime(date) {
    if (!date) return '未设置';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hour = String(d.getHours()).padStart(2, '0');
    const minute = String(d.getMinutes()).padStart(2, '0');
    return `${year}年${month}月${day}日 ${hour}:${minute}`;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '未签约',
      'active': '已开始',
      'completed': '已结束',
      'terminated': '已废除'
    };
    return statusMap[status] || '未知';
  },

  // 获取状态样式类
  getStatusClass(status) {
    const classMap = {
      'pending': 'status-pending',
      'active': 'status-active',
      'completed': 'status-completed',
      'terminated': 'status-terminated'
    };
    return classMap[status] || '';
  },

  // 跳转到合同原文页面
  goToContractText() {
    if (!this.data.contractId) {
      wx.showToast({
        title: '合同ID不存在',
        icon: 'none'
      });
      return;
    }

    // 查看模式：只传递 contractId 和 flow=view，通过 contractId 加载完整数据（包括签字）
    wx.navigateTo({
      url: `/pages/contract/index?contractId=${this.data.contractId}&flow=view`
    });
  },
  copyContractId() {
    wx.setClipboardData({
      data: this.data.contractId,
      success: () => {
        wx.showToast({
          title: '合同ID已复制',
          icon: 'success'
        });
      }
    });
  }
});

